<?php

namespace App\Admin\Forms;

use App\Models\ConsumableRecord;
use App\Models\ConsumableTrack;
use App\Models\InvitationCode;
use Carbon\Carbon;
use Dcat\Admin\Form\Row;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Widgets\Form;
use Exception;

class ConsumableRecordInForm extends Form
{
    /**
     * 处理表单提交逻辑.
     *
     * @param array $input
     *
     * @return JsonResponse
     */
    public function handle(array $input): JsonResponse
    {
        $type = $input['type'] ?? null;
        $number = $input['number'] ?? null;

        if (empty($type) || empty($number)) {
            return $this->response()
                ->error('缺少参数');
        }

        try {
            $data = [];
            for ($i = 0; $i < $number; $i++) {
                $data[$i]['type'] = $type;
                // $data[$i]['code'] = substr(base_convert(md5(uniqid(md5(microtime(true)), true)), 16, 10), 0, 6);
                $data[$i]['code'] = randCode(6);
                $data[$i]['created_at'] = Carbon::now();
                $data[$i]['updated_at'] = Carbon::now();
            }
            // dd($data);
            InvitationCode::insert($data);
            $return = $this->response()
                ->success('成功')
                ->refresh();
        } catch (Exception $e) {
            $return = $this
                ->response()
                ->error('失败' . $e->getMessage());
        }

        return $return;
    }

    /**
     * 构造表单.
     */
    public function form()
    {
        $this->row(function (Row $row) {
            $row->width(6)
                ->select('type')
                ->options(['medical' => '病例', 'register' => '注册'])
                ->required();
            $row->width(6)
                ->number('number', '数量')
                ->required();
            $row->width(6)
                ->select('region','分区')
                ->options(['1' => 'A', '2' => 'B','3'=>'C','4'=>'D'])
                ->required();
        });
    }
}
